package org.jeecg.modules.zhouAdmin.admin.fabeicCenter.serveic.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.gwcjava.jiekou.entity.MlccUserInfo;
import org.jeecg.modules.gwcjava.jiekou.mapper.MlccUserInfoMapper;
import org.jeecg.modules.zhouAdmin.admin.fabeicCenter.mapper.*;
import org.jeecg.modules.zhouAdmin.admin.fabeicCenter.pojo.*;
import org.jeecg.modules.zhouAdmin.admin.fabeicCenter.serveic.IFabricCenterService;
import org.jeecg.modules.zhouAdmin.admin.goodsCenter.util.GoodsUtil;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.mapper.MyMlccCompanyInfoMapper;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.pojo.MlccCompanyInfo;
import org.jeecg.modules.zhoupackage.mapper.MlccFabricInfoMapper;
import org.jeecg.modules.zhoupackage.mapper.MlccGroupInfoMapper;
import org.jeecg.modules.zhoupackage.mapper.MyMlccFabricDiscountGroupMapper;
import org.jeecg.modules.zhoupackage.pojo.MlccFabricDiscountGroup;
import org.jeecg.modules.zhoupackage.pojo.MlccFabricInfo;
import org.jeecg.modules.zhoupackage.pojo.MlccGroupInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 面料中心Service
 *
 * @author zxl
 * @since 20201027
 */
@SuppressWarnings("all")
@Service
public class FabeicCenterServiceImpl implements IFabricCenterService {

    @Autowired
    FabricCenterMapper mapper;

    @Autowired
    MlccGroupInfoMapper groupInfoMapper;

    @Autowired
    MlccFabricInfoMapper fabricInfoMapper;

    @Autowired
    MySysUserMapper userMapper;

    @Autowired
    MyBookletMapper bookletMapper;

    @Autowired
    MyMlccUserDiscountMapper userDiscountMapper;

    @Autowired
    MyMlccFabricDiscountGroupMapper fabricDiscountGroupMapper;

    @Autowired
    MyMlccFabricLadderPriceMapper fabricLadderPriceMapper;

    @Autowired
    MlccBookLetAndFabricMapper bookLetAndFabricMapper;

    @Autowired
    MyMlccCompanyInfoMapper companyInfoMapper;

    @Autowired
    MlccUserInfoMapper userInfoMapper;

    @Autowired
    MlccBookletFaMapper bookletFaMapper;

    @Autowired
    GoodsUtil goodsUtil;


    /**
     * 获取面料系列列表（面料组列表）
     *
     * @param page 分页器
     * @return
     */
    @Override
    public IPage<FabricGroup> getGroupList(Page<FabricGroup> page, String name, String price, String status, String code) {
        return mapper.getGroupList(page, name, price, status, code);
    }

    /**
     * 新增面料组
     *
     * @param name   面料组名称
     * @param price  价格
     * @param remake 备注
     * @return
     */
    @Override
    @Transactional
    public int addGroup(LoginUser user, String name, Double price, String remake) {
        if (price == null) {
            return -2;
        }
        MlccGroupInfo groupInfo = new MlccGroupInfo();
        groupInfo.setGroupName(name).setPrice(new BigDecimal(price)).setRemark(remake)
                .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname())
                .setStatus(2) // 新增的面料组默认为未启用
                .setGroupCode(UUID.randomUUID().toString().substring(0, 12));
        int insert = groupInfoMapper.insert(groupInfo);
        if (insert > 0) {
            // 向面料折扣体系与面料组关联表添加记录，需要遍历客户折扣类型表，给每个客户类型添加一个默认折扣默认为1
            List<MlccUserDiscount> discounts = userDiscountMapper.selectList(null);
            if (discounts != null && discounts.size() > 0) {
                discounts.stream().forEach(discount -> {
                    // 开始向 面料折扣体系与面料组关联表 插入数据
                    MlccFabricDiscountGroup discountGroup = new MlccFabricDiscountGroup();
                    discountGroup.setFabricDiscountSystemId(discount.getId()).setFabricGourpId(groupInfo.getId() + "");
                    fabricDiscountGroupMapper.insert(discountGroup);
                });
            }
        }
        return insert;
    }

    /**
     * 更新面料组信息
     *
     * @param groupID
     * @param name
     * @param price
     * @param remake
     * @return
     */
    @Override
    @Transactional
    public int updateGroup(Integer groupID, String name, Double price, String remake) {
        MlccGroupInfo groupInfo = groupInfoMapper.selectById(groupID);
        if (groupInfo == null) return 0;
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        groupInfo.setGroupName(name).setPrice(new BigDecimal(price)).setRemark(remake)
                .setUpdateBy(user.getRealname());
        return groupInfoMapper.updateById(groupInfo);
    }

    /**
     * 面料组下架
     *
     * @param groupID
     */
    @Override
    @Transactional
    public int shelves(String groupID) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MlccGroupInfo info = groupInfoMapper.selectById(groupID);
        if (info == null) return 0;
        info.setStatus(2).setUpdateBy(user.getRealname());
        int result = groupInfoMapper.updateById(info);
        if (result > 0) {
            // 把面料组名下的面料也下架
            QueryWrapper<MlccFabricInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("group_id", groupID).eq("status", 0).isNull("fabric_price");
            List<MlccFabricInfo> fabricInfos = fabricInfoMapper.selectList(wrapper);
            if (fabricInfos != null && fabricInfos.size() > 0) {
                fabricInfos.stream().forEach(fabric -> {
                    fabric.setStatus(2).setUpdateBy(user.getRealname());
                    int i = fabricInfoMapper.updateById(fabric);
                    if (i > 0) {
                        goodsUtil.offFabric(fabric.getId() + "");
                    }
                });
            }
        }
        return result;
    }

    /**
     * 面料组从新上架
     *
     * @param groupID 面料组ID
     */
    @Override
    public int groupUp(String groupID) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MlccGroupInfo info = groupInfoMapper.selectById(groupID);
        if (info == null) return 0;
        info.setStatus(0).setUpdateBy(user.getRealname());
        int result = groupInfoMapper.updateById(info);
        if (result > 0) {
            // 把面料组名下的面料也上架(过滤主推面料)
            QueryWrapper<MlccFabricInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("group_id", groupID).eq("status", 2).isNull("fabric_price");
            List<MlccFabricInfo> fabricInfos = fabricInfoMapper.selectList(wrapper);
            if (fabricInfos != null && fabricInfos.size() > 0) {
                fabricInfos.stream().forEach(fabric -> {
                    fabric.setStatus(0).setUpdateBy(user.getRealname());
                    fabricInfoMapper.updateById(fabric);
                });
            }
        }
        return result;
    }

    /**
     * 面料组恢复
     *
     * @param groupID 面料组ID
     */
    @Override
    public int huifu(String groupID) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MlccGroupInfo info = groupInfoMapper.selectById(groupID);
        if (info == null) return 0;
        info.setStatus(2).setUpdateBy(user.getRealname());
        int result = groupInfoMapper.updateById(info);
        /*if (result > 0) {
            // 把面料组名下的面料也恢复（下架状态）(过滤主推面料)
            QueryWrapper<MlccFabricInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("group_id", groupID).eq("status", 1).isNull("fabric_price");
            List<MlccFabricInfo> fabricInfos = fabricInfoMapper.selectList(wrapper);
            if (fabricInfos != null && fabricInfos.size() > 0) {
                fabricInfos.stream().forEach(fabric -> {
                    fabric.setStatus(2).setUpdateBy(user.getRealname());
                    fabricInfoMapper.updateById(fabric);
                });
            }
        }*/
        return result;
    }

    /**
     * 删除面料组
     *
     * @param groupID 面料组ID
     */
    @Override
    @Transactional
    public int deleteGroup(String groupID) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MlccGroupInfo info = groupInfoMapper.selectById(groupID);
        if (info == null) return 0;
        info.setStatus(1).setUpdateBy(user.getRealname());
        int result = groupInfoMapper.updateById(info);
        if (result > 0) {
            // 把面料组名下的面料也删除
//            mapper.getOutFabric(groupID, 1);
        }
        return result;
    }

    /**
     * 根据面料组ID获取名下面料数据列表
     *
     * @param groupID
     * @param page
     * @param fabricCode
     * @param gysCode
     * @param status
     * @return
     */
    @Override
    public IPage<FabricEntity> getFabricList(Page<FabricEntity> page, String groupID, String fabricCode, String gysCode, String status) {
        return mapper.getFabricList(page, groupID, fabricCode, gysCode, status);
    }

    /**
     * 删除面料
     *
     * @param fabricID
     * @return
     */
    @Override
    public int delFabric(String fabricID) {
        MlccFabricInfo info = fabricInfoMapper.selectById(fabricID);
        info.setStatus(1);
        int i = fabricInfoMapper.updateById(info);
        /*if (i > 0) {
            goodsUtil.delTonghe(fabricID, 1);
        }*/
        return i;
    }

    /**
     * 面料下架
     *
     * @param fabricID
     * @return
     */
    @Override
    public int serFabric(String fabricID) {
        MlccFabricInfo info = fabricInfoMapper.selectById(fabricID);
        info.setStatus(2);
        return fabricInfoMapper.updateById(info);
    }

    /**
     * 下架的面料重新上架
     *
     * @param fabricID 面料ID
     */
    @Override
    public int fabricUp(String fabricID) {
        MlccFabricInfo info = fabricInfoMapper.selectById(fabricID);
        info.setStatus(0);
        int i = fabricInfoMapper.updateById(info);
        if (i > 0) {
            goodsUtil.upFabric(fabricID);
        }
        return i;
    }

    /**
     * 获取主推面料列表
     *
     * @param page
     * @param fabricCode
     * @param gysCode
     * @param status
     * @return
     */
    @Override
    public IPage<FabricEntity> getFirstFabricList(Page<FabricEntity> page, String fabricCode, String gysCode, String status) {
        return mapper.getFirstFabricList(page, fabricCode, gysCode, status);
    }

    /**
     * 总后台获取面料详情
     *
     * @param fabricID
     * @return
     */
    @Override
    public MlccFabricInfo getFabricDetail(String fabricID) {
        MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(fabricID);
        MySysUser sysUser = userMapper.selectById(fabricInfo.getSysuserId());
        if (sysUser != null) {
            fabricInfo.setGysname(sysUser.getRealname());
        }
        return fabricInfo;
    }

    /**
     * 删除面料的恢复方式（状态变为已下架）
     *
     * @param id 面料id
     */
    @Override
    public int fabricHuifu(String id) {
        MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(id);
        fabricInfo.setStatus(2);
        return fabricInfoMapper.updateById(fabricInfo);
    }

    /**
     * 选择供应商
     *
     * @return
     */
    @Override
    public List<MySysUser> selectGYS() {
        QueryWrapper<MySysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("roletype", 1).eq("del_flag", 0);
        return userMapper.selectList(wrapper);
    }

    /**
     * 新增面料
     *
     * @param entity
     * @return
     */
    @Override
    public int addFabric(MlccFabricInfo entity) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        entity.setSysOrgCode(user.getOrgCode()).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname());
        int insert = fabricInfoMapper.insert(entity);
        if (insert > 0) {
            // 统合表添加记录
//            goodsUtil.addTonghe(entity.getId() + "", 1);
            // 商品表添加记录
            goodsUtil.addGoods(entity);
        }
        return insert;
    }

    /**
     * 更新面料信息
     *
     * @param entity
     * @return
     */
    @Override
    public int updateFabric(MlccFabricInfo entity) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        entity.setUpdateBy(user.getRealname());
        int i = fabricInfoMapper.updateById(entity);
        if (i > 0) {
            // 商品表更新
            goodsUtil.updateGoodsByFabric(entity, entity.getFabricCode());
        }
        return i;
    }

    /**
     * 新增主推面料  给这款面料设置一个单独的价格，暂时不需要阶梯价，不要一处面料系列
     *
     * @param fabricCode 面料编号
     * @param price      添加的价格
     * @param remark     备注
     */
    @Override
    public int addFirstFabric(String fabricCode, double price, String remark) {
        QueryWrapper<MlccFabricInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("fabric_code", fabricCode);
        MlccFabricInfo info = fabricInfoMapper.selectOne(wrapper);
        if (info == null) return -1;// 面料不存在
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 设置为主推面料之后，把这个面料移除面料组   （新需求，不移除面料系列，知识一个活动价格）
        //        .setGroupId(null)
        info.setUpdateBy(user.getRealname()).setFabricPrice(new BigDecimal(price)).setRemark(remark);
        return fabricInfoMapper.updateById(info);
//        return fabricInfoMapper.saveFirstFabric(info.getId(), price + "");
    }

    /**
     * 删除主推面料 本质就是把面料的默认价格变成0
     *
     * @param code 面料编号
     */
    @Override
    public int delFirstFabric(String id) {
        MlccFabricInfo info = fabricInfoMapper.selectById(id);
        if (info != null) {
            info.setFabricPrice(new BigDecimal(0));
            return fabricInfoMapper.updateById(info);
        }
        return 0;
    }

    /**
     * 删除没有发放的面料册
     *
     * @param id 面料册id
     */
    @Override
    public int delFabricBooklet(String id) {
        MlccFabricBooklet booklet = bookletMapper.selectById(id);
        if (booklet != null && booklet.getIssueNum() == 0) {
            return bookletMapper.deleteById(id);
        } else {
            return 0;
        }
    }

    /**
     * 获取面料册列表
     *
     * @param page  分页器
     * @param name  客户名称
     * @param phone 联系电话
     * @return
     */
    @Override
    public IPage<MlccFabricBooklet> listBooklets(Page<MlccFabricBooklet> page, String name, String phone) {
        QueryWrapper<MlccFabricBooklet> wrapper = new QueryWrapper<>();
        if (name != null && !"".equals(name)) {
            wrapper.like("booklet_name", name);
        }
        return bookletMapper.selectPage(page, wrapper);
    }

    /**
     * 新增面料册
     *
     * @param booklet 面料册实体
     * @return
     */
    @Override
    public int saveBooklet(MlccFabricBooklet booklet) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        booklet.setCreateBy(user.getRealname()).setUpdateBy(user.getRealname())
                .setSysOrgCode(user.getOrgCode());
        return bookletMapper.insert(booklet);
    }

    /**
     * 更新面料册
     *
     * @param booklet 面料册对象
     */
    @Override
    public int updateBooklet(MlccFabricBooklet booklet) {
        return bookletMapper.updateById(booklet);
    }

    /**
     * 面料册开始发放
     *
     * @param id 面料册id
     */
    @Override
    public int startfa(String id) {
        int result = 0;
        MlccFabricBooklet booklet = bookletMapper.selectById(id);
        if (booklet != null) {
            booklet.setStatus(2);
            result = bookletMapper.updateById(booklet);
        }
        return result;
    }

    /**
     * 面料册结束发放
     *
     * @param id 面料册id
     */
    @Override
    public int endfa(String id) {
        int result = 0;
        MlccFabricBooklet booklet = bookletMapper.selectById(id);
        if (booklet != null) {
            booklet.setStatus(3);
            result = bookletMapper.updateById(booklet);
        }
        return result;
    }

    /**
     * 面料批量导入
     *
     * @param list
     * @return
     */
    @Override
    public int importExcel(List<MlccFabricInfo> list, String group) {
        if (list == null || list.size() == 0) {
            return 0;
        }
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        int rsult = 0;
        for (MlccFabricInfo info : list) {
            if (info != null && info.getFabricCode() != null && info.getFabricCode().trim() != null && !"".equals(info.getFabricCode().trim())) {
                // 导入的供应商是名称，需要变成编号
                QueryWrapper<MySysUser> wrapper1 = new QueryWrapper<>();
                if (info.getGysname() == null || "".equals(info.getGysname())) {
                    throw new RuntimeException("面料 " + info.getFabricCode() + " 没有填写供应商信息");
                }
                wrapper1.eq("realname", info.getGysname().trim());
                MySysUser sysUser = userMapper.selectOne(wrapper1);
                info.setGroupId(group).setCreateBy(user.getUsername()).setUpdateBy(user.getUsername())
                        .setSysOrgCode(user.getOrgCode());
                if (sysUser != null) {
                    info.setSysuserId(sysUser.getId());
                }
                try {
                    rsult = fabricInfoMapper.insert(info);
                    // 统合表添加记录
//                goodsUtil.addTonghe(info.getId() + "", 1);
                    // 商品表添加记录
                    goodsUtil.addGoods(info);
                } catch (Exception e) {
                    System.out.println("结果" + rsult);
                    // 面料编号重复，那就去更新面料
                    QueryWrapper<MlccFabricInfo> wrapper = new QueryWrapper<>();
                    wrapper.eq("fabric_code", info.getFabricCode());
                    if (sysUser != null) {
                        info.setSysuserId(sysUser.getId());
                    }
                    rsult = fabricInfoMapper.update(info, wrapper);
                    if (rsult > 0) {
                        // 商品表更新
                        goodsUtil.updateGoodsByFabric(info, info.getFabricCode());
                    }
                }
            }
        }
        return rsult;
    }

    /**
     * 获取面料组的阶梯折扣
     *
     * @param groupid 面料组ID
     */
    @Override
    public List<MlccFabricLadderPrice> listGroupPrice(String groupid) {
        QueryWrapper<MlccFabricLadderPrice> wrapper = new QueryWrapper<>();
        wrapper.eq("group_id", groupid);
        return fabricLadderPriceMapper.selectList(wrapper);
    }

    /**
     * 添加折扣
     *
     * @param entity 参数对象
     */
    @Override
    public int saveGroupPrice(MlccFabricLadderPrice entity) {
        if (entity.getMinNumbers() >= entity.getMaxNumbers()) {
            return -1;
        }
        QueryWrapper<MlccFabricLadderPrice> wrapper = new QueryWrapper<>();
        wrapper.eq("group_id", entity.getGroupId());
        List<MlccFabricLadderPrice> prices = fabricLadderPriceMapper.selectList(wrapper);
        if (prices != null && prices.size() > 0) {
            for (MlccFabricLadderPrice price : prices) {
                if (entity.getMinNumbers() >= price.getMinNumbers() && entity.getMinNumbers() < price.getMaxNumbers()) {
                    return -1;
                }
            }
        }
        return fabricLadderPriceMapper.insert(entity);
    }

    /**
     * 获取面料模板
     */
    @Override
    public List<MlccFabricInfo> exportFabric() {
        Page<MlccFabricInfo> page = new Page<>(1, 2);
        List<MlccFabricInfo> records = fabricInfoMapper.selectPage(page, null).getRecords();
        if (records != null && records.size() > 0) {
            for (MlccFabricInfo record : records) {
                MySysUser user = userMapper.selectById(record.getSysuserId());
                if (user != null) {
                    record.setGysname(user.getRealname());
                }
            }
        }
        return records;
    }

    /**
     * 删除面料组阶梯价
     *
     * @param id 阶梯价主键id
     */
    @Override
    public int deleteGroupPrice(String id) {
        return fabricLadderPriceMapper.deleteById(id);
    }

    /**
     * 面料册导入面料
     *
     * @param file    上传的Excel文件
     * @param booklet 面料册ID
     */
    @Override
    public int importBookFabricExcel(List<MlccFabricInfo> list, String booklet) {
        if (list == null || list.size() == 0) {
            return 0;
        }
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        int rsult = 0;
        for (MlccFabricInfo info : list) {
            // 导入的面料必须在面料表中存在
            QueryWrapper<MlccFabricInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("fabric_code", info.getFabricCode());
            MlccFabricInfo count = fabricInfoMapper.selectOne(wrapper);
            if (count != null) {
                // 是否已经导入过？
                QueryWrapper<MlccBookletAndFabric> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("fabric_id", count.getId()).eq("boolet_id", booklet);
                int selectCount = bookLetAndFabricMapper.selectCount(wrapper1);
                if (selectCount == 0) {
                    // 插入数据
                    MlccBookletAndFabric bookLetAndFabric = new MlccBookletAndFabric();
                    bookLetAndFabric.setBooletId(booklet).setFabricId(count.getId() + "")
                            .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname());
                    rsult = bookLetAndFabricMapper.insert(bookLetAndFabric);
                }
            } else {
                throw new RuntimeException("文件中的面料 " + info.getFabricCode() + " 不存在");
            }
        }
        return rsult;
    }

    /**
     * 获取面料册下的面料
     *
     * @param page      分页器
     * @param bookletid 面料册id
     */
    @Override
    public IPage<MlccFabricInfo> listFabricFromBooklet(Page<MlccFabricInfo> page, String bookletid) {
        ArrayList<String> fabricidlist = new ArrayList<>();
        QueryWrapper<MlccBookletAndFabric> wrapper = new QueryWrapper<>();
        wrapper.eq("boolet_id", bookletid);
        // 面料册下所有的面料关联记录
        List<MlccBookletAndFabric> andFabrics = bookLetAndFabricMapper.selectList(wrapper);
        if (andFabrics != null && andFabrics.size() > 0) {
            for (MlccBookletAndFabric andFabric : andFabrics) {
                fabricidlist.add(andFabric.getFabricId());
            }
        }
        QueryWrapper<MlccFabricInfo> wrapper1 = new QueryWrapper<>();
        if (fabricidlist != null && fabricidlist.size() > 0) {
            wrapper1.in("id", fabricidlist);
        } else {
            wrapper1.eq("id", -1);
        }
        IPage<MlccFabricInfo> iPage = fabricInfoMapper.selectPage(page, wrapper1);
        // 赋予关联的id
        List<MlccFabricInfo> list = iPage.getRecords();
        if (list != null && list.size() > 0) {
            for (MlccFabricInfo fabricInfo : list) {
                QueryWrapper<MlccBookletAndFabric> wrapper2 = new QueryWrapper<>();
                wrapper2.eq("boolet_id", bookletid).eq("fabric_id", fabricInfo.getId());
                MlccBookletAndFabric one = bookLetAndFabricMapper.selectOne(wrapper2);
                if (one != null) {
                    fabricInfo.setBookandid(one.getId());
                }
            }
        }
        return iPage;
    }

    /**
     * 相处面料册下的面料
     *
     * @param id 关联表id
     */
    @Override
    public int delFabricFrombook(String id) {
        return bookLetAndFabricMapper.deleteById(id);
    }

    /**
     * 面料册详情
     *
     * @param id 面料册id
     */
    @Override
    public MlccFabricBooklet bookletDetail(String id) {
        return bookletMapper.selectById(id);
    }

    /**
     * 公司列表
     */
    @Override
    public IPage<MlccCompanyInfo> listCompany(Page<MlccCompanyInfo> page, String name) {
        QueryWrapper<MlccCompanyInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0);
        if (name != null && !"".equals(name)) {
            wrapper.like("company_name", name);
        }
        IPage<MlccCompanyInfo> iPage = companyInfoMapper.selectPage(page, wrapper);
        List<MlccCompanyInfo> list = iPage.getRecords();
        if (list != null && list.size() > 0) {
            for (MlccCompanyInfo companyInfo : list) {
                MlccUserInfo userInfo = userInfoMapper.selectById(companyInfo.getUserId());
                if (userInfo != null) {
                    companyInfo.setAddress(userInfo.getAddress());
                }
            }
        }
        return iPage;
    }

    /**
     * 发放面料册
     *
     * @param bookletid  面料册id
     * @param remark     备注
     * @param num        发放数量
     * @param companyids 公司id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addFa(String bookletid, String remark, Integer num, String[] companyids) {
        if (companyids == null && companyids.length == 0) {
            return 0;
        }
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MlccFabricBooklet booklet = bookletMapper.selectById(bookletid);
        if (booklet.getResidueNum() < num) {
            return -1;
        }
        if (booklet != null) {
            for (String companyid : companyids) {
                MlccCompanyInfo companyInfo = companyInfoMapper.selectById(companyid);
                if (companyInfo != null) {
                    if (booklet.getResidueNum() < num) {
                        throw new RuntimeException("面料册数量不足，无法发放！");
                    }
                    MlccBookletFa bookletFa = new MlccBookletFa();
                    bookletFa.setCompanyId(companyInfo.getId() + "").setBookletId(booklet.getId() + "")
                            .setNumber(num).setPrice(booklet.getPrice()).setAllPrice(booklet.getPrice()
                            .multiply(new BigDecimal(num))).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname())
                            .setRemark(remark);
                    int insert = bookletFaMapper.insert(bookletFa);
                    if (insert == 0) {
                        return 0;
                    } else {
                        System.out.println("发放数量=" + booklet.getIssueNum());
                        System.out.println("剩余数量=" + booklet.getResidueNum());
                        booklet.setIssueNum(booklet.getIssueNum() + num).setResidueNum(booklet.getResidueNum() - num);
                        bookletMapper.updateById(booklet);
                    }
                }
            }
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 面料册发放情况
     *
     * @param bookletid 面料册id
     * @param page      分页器
     */
    @Override
    public IPage<MlccBookletFa> listFafang(String bookletid, Page<MlccBookletFa> page) {
        QueryWrapper<MlccBookletFa> wrapper = new QueryWrapper<>();
        wrapper.eq("booklet_id", bookletid);
        IPage<MlccBookletFa> iPage = bookletFaMapper.selectPage(page, wrapper);
        List<MlccBookletFa> list = iPage.getRecords();
        if (list != null && list.size() > 0) {
            for (MlccBookletFa bookletFa : list) {
                MlccCompanyInfo companyInfo = companyInfoMapper.selectById(bookletFa.getCompanyId());
                if (companyInfo != null) {
                    bookletFa.setCompanyName(companyInfo.getCompanyName()).setCompanyCode(companyInfo.getCompanyCode())
                            .setAboutPhone(companyInfo.getAboutPhone());
                }
            }
        }
        return iPage;
    }

    /**
     * 删除发放记录
     *
     * @param id 发放id
     */
    @Override
    public int deleteFa(String id) {
        int result = 0;
        MlccBookletFa bookletFa = bookletFaMapper.selectById(id);
        if (bookletFa != null) {
            // 面料车册数量恢复
            MlccFabricBooklet booklet = bookletMapper.selectById(bookletFa.getBookletId());
            result = bookletFaMapper.deleteById(id);
            if (result > 0) {
                booklet.setResidueNum(booklet.getResidueNum() + bookletFa.getNumber())
                        .setIssueNum(booklet.getIssueNum() - bookletFa.getNumber());
                bookletMapper.updateById(booklet);
            }
        }
        return result;
    }

    /**
     * 面料列表的批量操作
     *
     * @param ids    面料id数组
     * @param status 状态
     */
    @Override
    public int fabricpi(String[] ids, Integer status) {
        int result = 0;
        if (ids != null && ids.length > 0) {
            for (String id : ids) {
                MlccFabricInfo info = fabricInfoMapper.selectById(id);
                if (info != null) {
                    info.setStatus(status);
                    result = fabricInfoMapper.updateById(info);
                }
            }
        }
        return result;
    }

    /**
     * 主推面料的导入
     *
     * @param list 面料集合
     */
    @Override
    public int importFirstFabricExcel(List<MlccFabricInfoFirst> list) {
        if (list == null || list.size() == 0) {
            throw new RuntimeException("文件为空，无法导入");
        }
        int result = 0;
        for (MlccFabricInfoFirst infoFirst : list) {
            QueryWrapper<MlccFabricInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("fabric_code", infoFirst.getFabricCode());
            MlccFabricInfo fabricInfo = fabricInfoMapper.selectOne(wrapper);
            if (fabricInfo == null) {
                throw new RuntimeException("面料 " + infoFirst.getFabricCode() + " 不存在");
            } else {
                // 将这个面料设置为主推面料
                fabricInfo.setFabricPrice(infoFirst.getFabricPrice()).setRemark(infoFirst.getRemark());
                result = fabricInfoMapper.updateById(fabricInfo);
            }
        }
        return result;
    }
}
